package gameEntities;

import javax.microedition.lcdui.game.LayerManager;

/**
 * The Class GameEntityManager manages the games entities.
 */
public class GameEntityManager {
	
	/**
	 * Instantiates a new game entity manager.
	 *
	 * @param layerManager the layer manager
	 */
	public GameEntityManager(LayerManager layerManager) {
		entities = new GameEntity[MAX_ENTITIES];
		for(int i = 0;i < MAX_ENTITIES;i++)
			entities[i] = null;
		
		this.layerManager = layerManager;
	}
	
	/**
	 * Adds a new game entity.
	 *
	 * @param ge the game entity
	 */
	public void Add(GameEntity ge) {
		for(int i = 0;i < MAX_ENTITIES;i++)
			if (entities[i] == null) {
				entities[i] = ge;
				layerManager.insert(ge.sprite, 0);
				break;
			}
	}
	
	/**
	 * Removes a game entity.
	 *
	 * @param ge the game entity
	 */
	public void Remove(GameEntity ge) {
		for(int i = 0;i < MAX_ENTITIES;i++)
			if (entities[i] == ge) {
				Remove(i);
				break;
			}
	}
	
	/**
	 * Calls the update-function for all game entities and removes
	 * old ones.
	 *
	 * @param deltaTime the delta time
	 */
	public void Update(float deltaTime) {
		for(int i = 0;i < MAX_ENTITIES;i++) {
			if (entities[i] != null)
			{
				if (entities[i].destroyable) {
					Remove(i);
					continue;
				}
				
				entities[i].Update(deltaTime);
			}
		}
	}
	
	/**
	 * Gets all game entities.
	 *
	 * @return all game entities[]
	 */
	public GameEntity[] GetEntities() {
		return entities;
	}
	
	/**
	 * Removes the game entity at a certain index.
	 *
	 * @param index the index
	 */
	private void Remove(int index)
	{
		layerManager.remove(entities[index].sprite);
		entities[index] = null;
	}
	
	private final int MAX_ENTITIES = 120;
	
	private GameEntity[] entities;
	
	private final LayerManager layerManager; 
}
